package asher.dotatbg.http.server;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

import org.apache.log4j.Logger;

import asher.dotatbg.constants.Constants;
import asher.dotatbg.http.connector.CoreConnector;
import asher.dotatbg.logfactory.LogFactory;

/**
 * Http部分的服务器，包含socket链接，解析request,和返回response等方面的关于http方面的通信
 * 使用单例模式，由启动器启动
 * @author AsherYuan
 */
public class HttpServer {

	private static Logger logger = LogFactory.getRootLogger();
	/**
	 * 使用单例模式
	 */
	private static HttpServer instance = null;
	
	/**
	 * 程序关闭命令标志
	 */
	private static boolean shutdown;
	
	public static synchronized HttpServer getInstance() {
		if(instance == null) {
			instance = new HttpServer();
		}
		return instance;
	}
	
	/**
	 * 私有的构造方法
	 */
	private HttpServer() {
		shutdown = false;
	}
	
	/**
	 * 服务器启动函数，做下列准备工作
	 * 建立ServerSocket服务器，循环监听浏览器发来的请求，并将连接上的请求传递给连接器
	 */
	public void start() {
		ServerSocket serverSocket = null;
		try {
			serverSocket = new ServerSocket(Constants.PORT, 1, InetAddress.getByName(Constants.IPADDRESS));
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		logger.info("Http服务器启动完成." + new Date().toString());
		
		while(!shutdown) {
			Socket socket = null;
			try {
				socket = serverSocket.accept();
				logger.info("接收到新的socket连接：" + socket.getInetAddress() + ":" + socket.getPort() + "........." + new Date().toString());
				new CoreConnector(socket);
			} catch (IOException e) {
				e.printStackTrace();
				continue;
			} finally {
				if(socket != null) {
					try {
						socket.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
					socket = null;
				}
			}
		}
	}
	
}
